package com.neuedu.dao.impl;

import com.neuedu.common.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;

public class TokenDao {
    public void setToken(String name, String token) {
        Connection con = DBUtil.getCon();
        String sql;
        try {
            sql = "select * from tokentemp where username=?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1, name);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                sql = "update tokentemp set token=?,newTime=? where username=?";
            } else {
                sql = "insert into tokentemp(token,newTime,username) values (?,?,?)";
            }
            rs.close();
            ps.close();
            ps = con.prepareStatement(sql);
            ps.setString(3, name);
            ps.setString(1, token);
            System.out.println(LocalDateTime.now());
            ps.setObject(2, LocalDateTime.now());
            ps.executeUpdate();
            rs.close();
            ps.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }

    public boolean getToken(String name, String token) {
        Connection con = DBUtil.getCon();
        String sql;
        try {
            sql = "select * from tokentemp where username=? and token=?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1, name);
            ps.setString(2, token);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return true;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }
}
